package com.ledi.guns.modular.ledipay.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.exception.BizExceptionEnum;
import com.ledi.guns.common.exception.BussinessException;
import com.ledi.guns.core.base.tips.SuccessTip;
import com.ledi.guns.core.base.tips.Tip;
import com.ledi.guns.core.util.DateUtil;
import com.ledi.guns.core.util.FileUtil;

// import cn.imexue.ec.web.util.WebConstants;

@Api
@RestController
@RequestMapping("/file")
public class ImageController {

	private static final Logger log = LoggerFactory.getLogger(ImageController.class);

	/**
	 * 图片上传的格式
	 */
	@Value("${app.access.img.type}")
	private String[] imgTypes;

	@Value("${cos.appid}")
	private String cosAppid;

	@Value("${cos.secret.id}")
	private String cosSecretId;

	@Value("${cos.secret.key}")
	private String cosSecretKey;

	@Value("${cos.region}")
	private String cosRegion;

	@Value("${cos.bucket.name}")
	private String cosBucketName;

	@Value("${cos.file.root.url}")
	private String cosFileRootUrl;

	@Value("${import.file.address}")
	private String importFileAddress;

	private static final String CODE_URL = "/image/codeImage?_=";

	/**
	 * @api {GET} /image/url 获取验证码地址
	 * @apiGroup common
	 * @apiName imageUrl
	 */
	@RequestMapping(value = "/url", method = RequestMethod.GET)
	public Tip getCodeUrl() {

		return SuccessTip.buildSuccess(CODE_URL + RandomUtils.nextInt());
	}

	/**
	 * @api {POST} /file/uploadImg 上传图片
	 * @apiGroup common
	 * @apiName imageUploadImg
	 * @apiParam {File} file 图片(类型:jpg,jpeg,gif,png,bmp,大小:2M)
	 * @apiSuccess {String} data 图片相对路径
	 * @apiError 2004 图片类型错误
	 */
	@ApiOperation("uploadImg")
	@ApiImplicitParams({
		@ApiImplicitParam(dataType = "file", name = "file", required = true, paramType = "form")
	})
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	public Tip uploadImg(@RequestParam("file") MultipartFile multipartFile) throws IOException {

		String fileName = multipartFile.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		if (!validateImgType(fileType)) {
			throw new AppCheckException("2004", "app.file.type.err", fileType, imgTypes);
		}
		if (multipartFile.getSize() > 2 * 1024 * 1024) {
			throw new AppCheckException("2005", "app.file.length.bigger");
		}
		String key = FileUtil.uploadFile(multipartFile, fileType, cosSecretId, cosSecretKey, cosBucketName, cosAppid);

		return SuccessTip.buildSuccess(key);
	}

	/**
	 * @api {POST} /file/uploadFile 上传文件
	 * @apiGroup common
	 * @apiName uploadFile
	 * @apiParam {File} file 图片(大小:100M)
	 * @apiSuccess {String} data 文件相对路径
	 * @apiError 2500 文件过大错误
	 */
	@ApiOperation("uploadFile")
	@ApiImplicitParams({
		@ApiImplicitParam(dataType = "file", name = "file", required = true, paramType = "form")
	})
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public Tip uploadFile(@RequestParam("file") MultipartFile multipartFile) throws IOException {

		String fileName = multipartFile.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

		if (multipartFile.getSize() > 100 * 1024 * 1024) {
			throw new AppCheckException("2005", "app.file.length.bigger");
		}
		String key = FileUtil.uploadFile(multipartFile, fileType, cosSecretId, cosSecretKey, cosBucketName, cosAppid);

		return SuccessTip.buildSuccess(key);
	}

	/**
	 * 判断文件格式
	 *
	 * @param type
	 * @return
	 */
	private boolean validateImgType(String type) {

		for (String imgType : imgTypes) {
			if (imgType.equalsIgnoreCase(type)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @api {POST} /file/importFile 上传文件（上传到服务器）
	 * @apiGroup common
	 * @apiName importFile
	 * @apiParam {File} file 图片(大小:100M)
	 * @apiSuccess {String} data 文件相对路径
	 * @apiError 2500 文件过大错误
	 */
	@RequestMapping(value = "/importFile", method = RequestMethod.POST)
	public Tip importFile(@RequestParam("file") MultipartFile file) {

		String fileName = "";
		try {

			if (file == null) {
				throw new BussinessException(BizExceptionEnum.FILE_NOT_FOUND);
			}
			if (file.getBytes().length > 100 * 1024 * 1024) {
				throw new BussinessException(BizExceptionEnum.FILE_LENGTH_BIGGER);
			}
			// 得到文件名
			fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			fileName = DateUtil.getAllTime() + function() + "." + fileType;
			File f = new File(importFileAddress + fileName);
			while (f.exists()) {
				f = new File(importFileAddress + DateUtil.getAllTime() + function() + "." + fileType);
			}
			if (!f.getParentFile().exists()) {
				// 如果目标文件所在的目录不存在，则创建父目录
				f.getParentFile().mkdirs();
			}

			if (file.getSize() > 0) {
				try {
					SaveFileFromInputStream(file.getInputStream(), importFileAddress, fileName);
				} catch (IOException e) {
					System.out.println(e.getMessage());
					throw new BussinessException(BizExceptionEnum.FILE_NOT_FOUND);
				}
			} else {
				throw new BussinessException(BizExceptionEnum.FILE_NOT_FOUND);
			}

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
			throw new BussinessException(BizExceptionEnum.FILE_NOT_FOUND);
		}
		return SuccessTip.buildSuccess(fileName);
	}

	/**
	 * 保存文件
	 *
	 * @param stream
	 * @param path
	 * @param filename
	 * @throws IOException
	 */
	public void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {

		FileOutputStream fs = new FileOutputStream(path + filename);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
	}

	public int function() {

		int n = 0;
		n = (int) (Math.random() * 100000);
		while (n < 10000 || !handle(n)) {
			n = (int) (Math.random() * 100000);
		}
		return n;
	}

	public boolean handle(int n) {

		int[] list = new int[5];
		for (int i = 0; i < 5; i++) {
			list[i] = n % 10;
			n = n / 10;
		}
		for (int i = 0; i < 5; i++) {
			for (int j = i + 1; j < 5; j++) {
				if (list[i] == list[j]) {
					return false;
				}
			}
		}
		return true;
	}
}
